package com.ruoyi.web.controller;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.framework.redis.CacheTool;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.biz.entity.BizUser;
import com.ruoyi.project.biz.service.IBizUserService;
import com.ruoyi.project.setting.security.utils.UserUtils;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.redis.cache.CacheKey;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Date;

/**
 * 用户表(BizUser) 控制层
 *
 * @author dyun
 */
@RestController
@RequestMapping("biz/user")
@AllArgsConstructor
public class BizUserController extends BaseController {

    private final IBizUserService bizUserService;

    /**
     * 详情
     */
    @GetMapping("/detail")
    public R<BizUser> detail() {
        Long id = UserUtils.currentLoginUser().getUserId();
        return success(bizUserService.getById(id));
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/partialupdate")
    public R partialupdate(@RequestBody BizUser bizUser) {
        Long id = UserUtils.currentLoginUser().getUserId();
        BizUser updateUser = new BizUser();
        updateUser.setId(id);
        updateUser.setAvatar(bizUser.getAvatar());
        if ($.isNotBlank(bizUser.getNickName())) {
            // 一个月仅允许修改一次
            Date now = new Date();
            long millis = DateUtil.endOfMonth(now).getTime() - now.getTime();
            CacheKey cacheKey = new CacheKey("nickname:" + id, Duration.ofMillis(millis));
            Object o = CacheTool.getMicaRedisCache().get(cacheKey);
            if (o != null) {
                throw new CustomException("本月您已修改，请下个月再来！");
            } else {
                CacheTool.getMicaRedisCache().set(cacheKey, bizUser.getNickName());
            }
            updateUser.setNickName(bizUser.getNickName());
            
        }
        return status(bizUserService.updateById(updateUser));
    }
}